package com.hifar.sso.service.impl;

import com.hifar.abi.base.utils.AuthCfgUtils;
import com.hifar.plat.user.pojo.BaseOrgUserPlat;
import com.hifar.plat.user.service.IBaseOrgUserService;
import com.hifar.sso.model.SSOUser;
import com.hifar.sso.service.SSOUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * SSO用户服务实现类
 *
 * @author system
 * @since 1.0.0
 */
@Service
public class SSOUserServiceImpl implements SSOUserService {

    private static final Logger logger = LoggerFactory.getLogger(SSOUserServiceImpl.class);

    @Autowired
    private IBaseOrgUserService baseOrgUserService;

    // TODO: 注入实际的用户数据访问层
    // @Autowired
    // private UserMapper userMapper;

    // @Autowired
    // private UserRoleMapper userRoleMapper;

    // @Autowired
    // private UserPermissionMapper userPermissionMapper;

    @Override
    public SSOUser authenticate(String username, String password) {
        try {
            logger.info("开始用户认证，用户名: {}", username);

            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                return null;
            }

            // 验证密码
            if (!validatePassword(username, password)) {
                return null;
            }

            // 获取用户信息
            SSOUser user = getUserByUsername(username);
            if (user == null) {
                return null;
            }
            logger.info("用户认证成功，用户ID: {}", user.getUserId());
            return user;

        } catch (Exception e) {
            logger.error("用户认证异常", e);
            return null;
        }
    }

    @Override
    public SSOUser getUserById(String userId) {
        try {
            if (!StringUtils.hasText(userId)) {
                return null;
            }
            BaseOrgUserPlat orgUserPlat = baseOrgUserService.getById(userId);
            if (orgUserPlat == null) {
                return null;
            }

            SSOUser ssoUser = new SSOUser();
            ssoUser.setUserId(orgUserPlat.getId());
            ssoUser.setUsername(orgUserPlat.getUserCode());
            ssoUser.setCreateTime(new Date(orgUserPlat.getCreateTime()));
            ssoUser.setRealName(orgUserPlat.getIdName());
            ssoUser.setEmail(orgUserPlat.getEmail());
            ssoUser.setPhone(orgUserPlat.getTelephone());
            ssoUser.setTenantId(orgUserPlat.getTenantId());
            ssoUser.setDepartmentId(orgUserPlat.getDeptId());
            ssoUser.setDepartmentName(orgUserPlat.getDeptName());
            return ssoUser;

        } catch (Exception e) {
            logger.error("根据用户ID获取用户信息异常", e);
            return null;
        }
    }

    @Override
    public SSOUser getUserByUsername(String username) {
        try {
            if (!StringUtils.hasText(username)) {
                return null;
            }

            BaseOrgUserPlat baseOrgUserPlat = baseOrgUserService.queryByUserCode(username);
            SSOUser ssoUser = new SSOUser();
            ssoUser.setUserId(baseOrgUserPlat.getId());
            ssoUser.setUsername(username);
            ssoUser.setRealName(baseOrgUserPlat.getIdName());
            ssoUser.setEmail(baseOrgUserPlat.getEmail());
            ssoUser.setPhone(baseOrgUserPlat.getTelephone());
            ssoUser.setTenantId(baseOrgUserPlat.getTenantId());
            ssoUser.setDepartmentId(baseOrgUserPlat.getDeptId());
            ssoUser.setDepartmentName(baseOrgUserPlat.getDeptName());
            return ssoUser;

        } catch (Exception e) {
            logger.error("根据用户名获取用户信息异常", e);
            return null;
        }
    }

    @Override
    public boolean updateUser(SSOUser user) {
        try {
            if (user == null || !StringUtils.hasText(user.getUserId())) {
                return false;
            }

            // TODO: 更新数据库用户信息
            // return userMapper.updateById(user) > 0;

            logger.info("用户信息更新成功，用户ID: {}", user.getUserId());
            return true;

        } catch (Exception e) {
            logger.error("更新用户信息异常", e);
            return false;
        }
    }

    @Override
    public List<String> getUserPermissions(String userId) {
        try {
            if (!StringUtils.hasText(userId)) {
                return new ArrayList<>();
            }

            // TODO: 从数据库获取用户权限
            // return userPermissionMapper.selectPermissionsByUserId(userId);

            // 临时模拟数据
            List<String> permissions = new ArrayList<>();
            permissions.add("user:read");
            permissions.add("user:write");
            permissions.add("system:admin");
            return permissions;

        } catch (Exception e) {
            logger.error("获取用户权限异常", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<String> getUserRoles(String userId) {
        try {
            if (!StringUtils.hasText(userId)) {
                return new ArrayList<>();
            }

            // TODO: 从数据库获取用户角色
            // return userRoleMapper.selectRolesByUserId(userId);

            // 临时模拟数据
            List<String> roles = new ArrayList<>();
            roles.add("admin");
            roles.add("user");
            return roles;

        } catch (Exception e) {
            logger.error("获取用户角色异常", e);
            return new ArrayList<>();
        }
    }

    @Override
    public boolean validatePassword(String username, String password) {
        try {
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                return false;
            }
            BaseOrgUserPlat baseOrgUserPlat = baseOrgUserService.queryByUserCode(username);
            if (baseOrgUserPlat == null) {
                return false;
            }
            String pwd = com.hifar.fw.utils.lang.StringUtils.trimNull(baseOrgUserPlat.getPwd());
            String salt = com.hifar.fw.utils.lang.StringUtils.trimNull(baseOrgUserPlat.getSalt());
            String entPwd = AuthCfgUtils.encryptPwd(password + salt);
            return Objects.equals(pwd, entPwd);
        } catch (Exception e) {
            logger.error("验证用户密码异常", e);
            return false;
        }
    }
}
